package com.duojuhe.coremodule.tracking.service.impl;

import com.duojuhe.cache.SystemDictCache;
import com.duojuhe.common.annotation.DataScopeFilter;
import com.duojuhe.common.bean.UserTokenInfoVo;
import com.duojuhe.common.constant.DataScopeConstants;
import com.duojuhe.common.exception.base.DuoJuHeException;
import com.duojuhe.common.result.ErrorCodes;
import com.duojuhe.common.result.PageResult;
import com.duojuhe.common.result.ServiceResult;
import com.duojuhe.common.utils.idgenerator.UUIDUtils;
import com.duojuhe.common.utils.page.PageHelperUtil;
import com.duojuhe.coremodule.BaseService;
import com.duojuhe.coremodule.system.entity.SystemDict;
import com.duojuhe.coremodule.tracking.entity.TrackingProduct;
import com.duojuhe.coremodule.tracking.entity.TrackingProductCategory;
import com.duojuhe.coremodule.tracking.mapper.TrackingProductCategoryMapper;
import com.duojuhe.coremodule.tracking.mapper.TrackingProductMapper;
import com.duojuhe.coremodule.tracking.pojo.dto.productcategory.*;
import com.duojuhe.coremodule.tracking.service.TrackingProductCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class TrackingProductCategoryServiceImpl extends BaseService implements TrackingProductCategoryService {
    @Resource
    private SystemDictCache systemDictCache;
    @Resource
    private TrackingProductCategoryMapper trackingProductCategoryMapper;
    @Resource
    private TrackingProductMapper trackingProductMapper;

    /**
     * 【查询所有产品分类】产品分类管理
     * @param req
     * @return
     */
    @DataScopeFilter
    @Override
    public ServiceResult<PageResult<List<QueryTrackingProductCategoryPageRes>>> queryTrackingProductCategoryPageResList(QueryTrackingProductCategoryPageReq req) {
        PageHelperUtil.orderByAndStartPage(req, "sort desc,createTime desc, categoryId desc");
        List<QueryTrackingProductCategoryPageRes> list = trackingProductCategoryMapper.queryTrackingProductCategoryPageResList(req);
        for (QueryTrackingProductCategoryPageRes res:list){
            SystemDict dictStatus = systemDictCache.getSystemDictByDictCode(res.getStatusCode());
            res.setStatusName(dictStatus.getDictName());
            res.setStatusColor(dictStatus.getDictColor());
        }
        return PageHelperUtil.returnServiceResult(req, list);
    }



    /**
     * 【查询所有产品分类】查询可供前端选择使用的产品分类
     * @param req
     * @return
     */
    @DataScopeFilter(dataScope = DataScopeConstants.TENANT_ALL_DATA)
    @Override
    public ServiceResult<List<QuerySelectTrackingProductCategoryRes>> querySelectNormalTrackingProductCategoryResList(QuerySelectTrackingProductCategoryReq req) {
        PageHelperUtil.defaultOrderBy("sort desc,createTime desc, categoryId desc");
        List<QuerySelectTrackingProductCategoryRes> list = trackingProductCategoryMapper.querySelectNormalTrackingProductCategoryResList(req);
        return ServiceResult.ok(list);
    }


    /**
     * 【保存】产品分类产品
     * @param req
     * @return
     */
    @Override
    public ServiceResult saveTrackingProductCategory(SaveTrackingProductCategoryReq req) {
        //分类ID
        String categoryId = UUIDUtils.getUUID32();
        //当前登录用户
        UserTokenInfoVo userTokenInfoVo = getCurrentLoginUserInfoDTO();
        //当前时间
        Date date = new Date();
        TrackingProductCategory category = new TrackingProductCategory();
        category.setCategoryId(categoryId);
        category.setCategoryName(req.getCategoryName());
        category.setCreateTime(date);
        category.setUpdateTime(date);
        category.setSort(req.getSort());
        category.setCreateUserId(userTokenInfoVo.getUserId());
        category.setUpdateUserId(userTokenInfoVo.getUserId());
        category.setCreateDeptId(userTokenInfoVo.getCreateDeptId());
        category.setTenantId(userTokenInfoVo.getTenantId());
        category.setStatusCode(req.getStatusCode());
        trackingProductCategoryMapper.insertSelective(category);
        return ServiceResult.ok(categoryId);
    }

    /**
     * 【修改】产品分类产品
     * @param req
     * @return
     */
    @Override
    public ServiceResult updateTrackingProductCategory(UpdateTrackingProductCategoryReq req) {
        //分类ID
        String categoryId = req.getCategoryId();
        TrackingProductCategory categoryOld = trackingProductCategoryMapper.selectByPrimaryKey(categoryId);
        if (categoryOld==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //当前登录用户
        UserTokenInfoVo userTokenInfoVo = getCurrentLoginUserInfoDTO();
        //当前时间
        Date date = new Date();
        TrackingProductCategory category = new TrackingProductCategory();
        category.setCategoryId(categoryId);
        category.setCategoryName(req.getCategoryName());
        category.setUpdateTime(date);
        category.setSort(req.getSort());
        category.setUpdateUserId(userTokenInfoVo.getUserId());
        category.setStatusCode(req.getStatusCode());
        trackingProductCategoryMapper.updateByPrimaryKeySelective(category);
        return ServiceResult.ok(categoryId);
    }

    /**
     * 【删除】根据产品分类ID删除产品分类，注意一次仅能删除一个产品分类，存在绑定关系的则不能删除
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServiceResult deleteTrackingProductCategoryByCategoryId(TrackingProductCategoryIdReq req) {
        String categoryId = req.getCategoryId();
        TrackingProductCategory categoryOld = trackingProductCategoryMapper.selectByPrimaryKey(categoryId);
        if (categoryOld == null) {
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //判断分类是否被产品关联使用
        checkRelationTrackingProduct(categoryId);
        //分类删除
        trackingProductCategoryMapper.deleteByPrimaryKey(categoryId);
        return ServiceResult.ok(categoryId);
    }


    /**
     * 【私有方法，辅助其他接口方法使用】 根据分类id查询是否存在产品关联
     */
    private void checkRelationTrackingProduct(String categoryId) {
        if (StringUtils.isBlank(categoryId)){
            throw new DuoJuHeException(ErrorCodes.TRACKING_PRODUCT_CATEGORY_RELATION_PRODUCT_NOT_DELETE);
        }
        Example example = new Example(TrackingProduct.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("productCategoryId", categoryId);
        if(trackingProductMapper.selectByExample(example).size()>0){
            throw new DuoJuHeException(ErrorCodes.TRACKING_PRODUCT_CATEGORY_RELATION_PRODUCT_NOT_DELETE);
        }
    }
}
